package util;

import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;

import java.sql.*;
import javax.sql.DataSource;

public class DBUtil {
    private static volatile DataSource DATA_SOURCE = null;

    /**
     * 获取数据库URL
     * @return
     */
    public static String getUrl(){
//        URL classesURL = DBUtil.class.getClassLoader().getResource("./");
//        String dir = new File(classesURL.getPath()).getParent();
//        String url = "jdbc:sqlite://" + dir + File.separator +"file_meta.db";
        String url = "jdbc:sqlite://D:\\CodeAPP\\sqlite\\SearchFile.db";
        return url;
    }
    /**
     *提供获取数据库连接词的功能
     * 使用单例模式(多线程安全)
     * 回顾多线程安全版本的单例模式:
     * 1.为什么在最外层判断是否为null?
     * 2.synchronized加锁以后,为什么还要判断是否为null
     * 3.为什么Datasource类变量要使用volatile关键字修饰
     * 多线程操作:原子性,可见性(从主内存拷贝到工作内存),有序性
     * synchronized保证前三个特性,volatile保证可见性,有序性
     * @return
     */
    private static DataSource getDataSource(){
        if(DATA_SOURCE == null){
            synchronized (DBUtil.class){
                if(DATA_SOURCE == null){
                    SQLiteConfig config = new SQLiteConfig();
                    config.setDateStringFormat(Util.DATA_PATTERN);
                    DATA_SOURCE = new SQLiteDataSource();
                    ((SQLiteDataSource) DATA_SOURCE).setUrl(getUrl());
                }
            }
        }
        return DATA_SOURCE;
    }
    //获取数据库连接
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }
    //关闭资源
    public static void close(Connection connection, Statement statement){
        close(connection,statement,null);
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        try {
            if(connection != null){
                connection.close();
            }
            if(statement != null){
                statement.close();
            }
            if(resultSet != null){
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭资源失败",e);
        }
    }

    public static void main(String[] args) {
        try {
            Connection connection = getConnection();
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
